var prefix = '?XDEBUG_SESSION_START=16463';
const api = {
    request(url, data = {}, method = "GET", silence = false) {

        return new Promise(function (resolve, reject) {

            !silence && store.commit('requestCounter', 1)

            var conf = {
                method: method,
                url: url + prefix,
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8',
                    'token': Lockr.get('token'),
                    'hq-token': Lockr.get('token')
                }
            }

            if(method == 'POST'){
                conf.data = data
            }
            else{
                conf.params = data
            }

            axios(conf).then((res) => {
                !silence && store.commit('requestCounter', -1)
                if (res.data.status == 0) {
                    !silence && _g.toast('warn', res.data.message)
                    reject(res)
                }
                else {
                    resolve(res.data)
                }
            }).catch((res) => {
                !silence && store.commit('requestCounter', -1)
                if (res.response) {

                    if (res.response.status == 401) {
                        _g.toast('warn', '登录失效,请重新登录!')
                        Lockr.rm('token')
                        Lockr.rm('user');
                        if (router.currentRoute.name != 'login' && router.currentRoute.fullPath != '/loan') {
                            console.log('relogin:' + new Date().getTime())
                            router.replace({path: '/login', query: {redirect: router.currentRoute.fullPath}})
                        }
                        return
                    }
                    else if (res.response.status == 403) {
                        _g.toast('warn', '无权限操作!')
                        return
                    }
                    else {
                        _g.toast('warn', res.response.statusText)
                        return
                    }
                }
                else {
                    !silence && _g.toast('warn', res.message)
                    return
                }

            })
        })
    }
};

export default api
